﻿using Business;
using MB.Orm.DB;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.OleDb;
using System.IO;
using WoChu.Infrastructure.Web;
using WoChu.Infrastructure.ModelCommmon;
using WoChu.WMS.Application.Dto;
using WoChu.WMS.Web.Common;
using Business.Dto;
using Business.Service;
using WoChu.Infrastructure.Collection;
using System.Dynamic;
using Public;

namespace MvcAppWeb.Controllers
{
    public class BaseDataController : Controller
    {
        public LogUntity _Log = new LogUntity();
        public CommonDataService _CommonDataService = new CommonDataService();
        public AppUserList CurrentUser
        {
            get
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return model;
            }
        }

        public bool IsAdminUser { 
            get {

                return Constant.AdminUserCode.ToLower().Split(',').IndexOf<string>(this.CurrentUser.USERCODE.ToLower()) >= 0; 
            } 
        }

        #region 公共事件重写
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Session["UserInfo"] == null)
            {
                if (Request.IsAjaxRequest())
                {
                    var json = new JsonResult() { Data = new AjaxResult().SetError("请重新登录！"), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                    var response = filterContext.HttpContext.Response;
                    response.Clear();
                    response.StatusCode = 200;
                    response.TrySkipIisCustomErrors = true;
                    filterContext.Result = json;

                }
                else
                    filterContext.Result = RedirectToAction("LogOn", "Account");
            }

            base.OnActionExecuting(filterContext);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            string title = string.Format("controller:{0} action:{1}", filterContext.RouteData.Values["controller"], filterContext.RouteData.Values["action"]);
            _Log.LogError(filterContext.Exception, title);
            base.OnException(filterContext);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;
            if (jsonResult != null)
            {
                filterContext.Result = new JsonNetResult
                {
                    ContentEncoding = jsonResult.ContentEncoding,
                    ContentType = string.IsNullOrEmpty(jsonResult.ContentType ) ? "application/json" : jsonResult.ContentType,
                    Data = ConvertPageJson(jsonResult.Data),
                    JsonRequestBehavior = jsonResult.JsonRequestBehavior
                };
            }
            base.OnActionExecuted(filterContext);
        }

        object ConvertPageJson(object data)
        {
            if (data == null) return null;

            IPageInfo page = data as IPageInfo;
            if (data.GetType().IsGenericType && page != null)
            {
                return page.GetDicts();                
            }
            return data;
        }
        #endregion

        #region 公共数据加载
        /// <summary>
        /// 库位列表
        /// </summary>
        /// <param name="IsSetAll">是否加全部项，0为是</param>
        /// <returns></returns>
        public JsonResult CellNoList(int IsSetAll = 1, int? AllValue = null)
        {
            List<CellNo> lstCellNo = new List<CellNo>();
            NewCommon nc = new NewCommon();
            lstCellNo = nc.GetCellNoList();
            if (IsSetAll <= 0)
            {
                CellNo c = new CellNo();
                c.CELLNO = "全部";
                if (AllValue != null)
                    c.FIELDVALUE = AllValue.Value;
                lstCellNo.Insert(0, c);
            }
            return Json(lstCellNo);
        }

        /// <summary>
        ///ERP报表使用 库位列表
        /// </summary>
        /// <param name="IsSetAll">是否加全部项，0为是</param>
        /// <returns></returns>
        public JsonResult CellNoListERP(int IsSetAll = 1)
        {
            var list = _CommonDataService.GetCellNolist().ToList();
            if (IsSetAll <= 0)
            {
                dynamic c;
                c = new ExpandoObject();
                c.NAME = "全部";
                list.Insert(0, c);
            }
            return Json(list);
        }

        /// <summary>
        /// 供应商
        /// </summary>
        /// <returns></returns>
        public JsonResult VenderList()
        {
            var list = _CommonDataService.GetVenderList();
            return Json(list);
        }

        /// <summary>
        /// 订单状态
        /// </summary>
        /// <returns></returns>
        public JsonResult OrderFlagList()
        {
            string[] condition = { "20", "40", "100" };
            var list = _CommonDataService.GetFlagList().Where(s => condition.IndexOf<string>((string)s.CODE) >= 0);
            return Json(list);
        }

        /// <summary>
        /// 下架单状态
        /// </summary>
        /// <returns></returns>
        public JsonResult DownOrderFlagList()
        {
            string[] condition = { "40", "100","0" };
            var list = _CommonDataService.GetFlagList().Where(s => condition.IndexOf<string>((string)s.CODE) >= 0);
            return Json(list);
        }

        /// <summary>
        /// 货位类型
        /// </summary>
        /// <returns></returns>
        public JsonResult LocationTypeList()
        {            
            var list = _CommonDataService.GetLocationTypeList();
            return Json(list);
        }

        /// <summary>
        /// 仓库类别
        /// </summary>
        /// <returns></returns>
        public JsonResult WarehouseList()
        {
            var list = _CommonDataService.GetWarehouseList();
            return Json(list);
        }

        /// <summary>
        /// 上架原因
        /// </summary>
        /// <returns></returns>
        public JsonResult UpObjectTypeList()
        {
            var list = _CommonDataService.GetUpObjectTypeList();
            return Json(list);
        }

        /// <summary>
        /// 下架原因
        /// </summary>
        /// <returns></returns>
        public JsonResult DownObjectTypeList()
        {
            var list = _CommonDataService.GetDownObjectTypeList();
            return Json(list);
        }

        /// <summary>
        /// 下架类型
        /// </summary>
        /// <returns></returns>
        public JsonResult DownTypeList()
        {
            var list = _CommonDataService.GetDownTypeList();
            return Json(list);
        }
        /// <summary>
        /// 是否启用
        /// </summary>
        /// <returns></returns>
        public JsonResult StatusList()
        {
            var list = _CommonDataService.GetStatusList();
            return Json(list);
        }

        public JsonResult UserList()
        {
            var retData = new object();
            NewCommon nc = new NewCommon();
            retData = nc.GetUserList().ToList();
            return Json(retData);
        }

        /// <summary>
        /// 下架指令类型
        /// </summary>
        /// <param name="IsSetAll"></param>
        /// <returns></returns>
        public JsonResult OffShelvesTypeList(int IsSetAll = 1)
        {
            var list = _CommonDataService.GetOffShelvesTypeList().ToList();
            if (IsSetAll <= 0)
            {
                dynamic c;
                c = new ExpandoObject();
                c.CODE = -1;
                c.NAME = "全部";
                list.Insert(0, c);
            }
            return Json(list);
        }
        #endregion

        public string ImportFile(HttpPostedFileBase file, out DataTable ImportTable, out string ImportString)
        {
            string sjson = string.Empty;
            ImportTable = new DataTable();
            ImportString = string.Empty;

            string FileName;
            string savePath;
            if (file == null || file.ContentLength <= 0)
            {
                sjson = "{success:false,msg:'文件不能为空'}";
                return sjson;
            }
            string filename = Path.GetFileName(file.FileName);
            int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
            string fileEx = Path.GetExtension(filename);//获取上传文件的扩展名
            string NoFileName = Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
            int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
            string FileType = ".xls,.xlsx,.txt";//定义上传文件的类型字符串

            FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
            if (!FileType.Contains(fileEx))
            {
                sjson = "{success:false,msg:'文件类型不对，只能导入xls和xlsx或者txt格式的文件'}";
                return sjson;
            }
            if (filesize >= Maxsize)
            {
                sjson = "{success:false,msg:'上传文件超过4M，不能上传'}";
                return sjson;
            }
            string path = AppDomain.CurrentDomain.BaseDirectory + "upload/";
            savePath = Path.Combine(path, FileName);
            file.SaveAs(savePath);

            if (fileEx == ".txt")
            {
                StreamReader sr = new StreamReader(savePath, System.Text.Encoding.Default);
                ImportString = sr.ReadToEnd();
                ImportString = ImportString.Replace("\r\n", "").Replace("\n", "");
                sr.Close();
                return sjson;
            }
            string strConn;
            strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + savePath + ";" + "Extended Properties=Excel 12.0";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable sheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { null, null, null, "Table" });
            string[] sheet = new string[sheetName.Rows.Count];
            for (int i = 0, j = sheetName.Rows.Count; i < j; i++)
            {
                sheet[i] = sheetName.Rows[i]["TABLE_NAME"].ToString();
            }
            OleDbDataAdapter myCommand = new OleDbDataAdapter(string.Format("select * from [{0}]", sheet[0]), strConn);
            DataSet myDataSet = new DataSet();
            try
            {
                myCommand.Fill(myDataSet, "ExcelInfo");
            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
                return sjson;
            }
            ImportTable = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
            return sjson;
        }

        public string NewTimeStamp(string strFileName)
        {
            //生成文件名: 当前年月日小时分钟秒+ 随机数
            Random rd = new Random(int.Parse(DateTime.Now.ToString("MMddhhmmss")));
            strFileName += DateTime.Now.ToString("yyyyMMdd")
                + DateTime.Now.Hour
                + DateTime.Now.Minute
                + DateTime.Now.Second
                + rd.Next(999999).ToString()
                + ".xls";
            return strFileName;
        }


    }
}
